package br.com.ia.test;

import java.util.Hashtable;
import java.util.Vector;

public class WorkingMemory {

	Vector assertions;

	WorkingMemory() {
		assertions = new Vector();
	}

	public boolean contains(String assertion) {
		return assertions.contains(assertion);
	}

	public void addAssertion(String theAssertion) {
		System.out.println("ADD:" + theAssertion);
		assertions.addElement(theAssertion);
	}

	public Vector matchingAssertions(Vector theAntecedents) {
		Vector bindings = new Vector();
		return matchable(theAntecedents, 0, bindings);
	}

	private Vector matchable(Vector theAntecedents, int n, Vector bindings) {
		if (theAntecedents != null && n == theAntecedents.size()) {
			return bindings;
		} else if (n == 0) {
			boolean success = false;
			for (int i = 0; i < assertions.size(); i++) {
				Hashtable binding = new Hashtable();
				if ((new Matcher()).matching((String) theAntecedents
						.elementAt(n), (String) assertions.elementAt(i),
						binding)) {
					bindings.addElement(binding);
					success = true;
				}
			}
			if (success) {
				return matchable(theAntecedents, n + 1, bindings);
			} else {
				return null;
			}
		} else {
			boolean success = false;
			Vector newBindings = new Vector();
			for (int i = 0; i < bindings.size(); i++) {
				for (int j = 0; j < assertions.size(); j++) {
					if ((new Matcher()).matching((String) theAntecedents
							.elementAt(n), (String) assertions.elementAt(j),
							(Hashtable) bindings.elementAt(i))) {
						newBindings.addElement(bindings.elementAt(i));
						success = true;
					}
				}
			}
			if (success) {
				return matchable(theAntecedents, n + 1, newBindings);
			} else {
				return null;
			}
		}
	}

	public String toString() {
		return assertions.toString();
	}

}
